//
//  AppDelegate.m
//  CharonTVProject
//
//  Created by karong on 2023/6/7.
//

#import "AppDelegate.h"
#import "FirebaseCore.h"
#import "Firebase.h"
#import "BaseTabBarController.h"
#import "IQKeyboardManager.h"
#import "WSLoginController.h"
#import "WSAppDelegateRequest.h"
#import <FBSDKCoreKit/FBSDKCoreKit.h>
#import <FBSDKLoginKit/FBSDKLoginKit.h>
#import <AppTrackingTransparency/AppTrackingTransparency.h>
#import <AppsFlyerLib/AppsFlyerLib.h>
#import "WSFirstPopupViewController.h"

#import <WXApi.h>
#import <UMCommon/UMConfigure.h>
#import <UMShare/UMShare.h>
//#import <UMPush/UMessage.h>

@interface AppDelegate () <AppsFlyerLibDelegate,WXApiDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [FIRApp configure];
    [self initAppsFlyer];
    
    [self initSDK];
    [GADMobileAds.sharedInstance startWithCompletionHandler:nil];
    [self createFaceBook:application didFinishLaunchingWithOptions:launchOptions];
    [self initIQKeyboardManager];
    [self initAD];
    [self initMainPage];
    [self loadConfig];
    
    return YES;
}

- (void)initSDK{
    [WXApi registerApp:@"" universalLink:@"https://dm.3dliveo.com/"];
    [WXApi startLogByLevel:WXLogLevelDetail logBlock:^(NSString * _Nonnull log) {
        NSLog(@"log=======%@",log);
    }];
    
    [UMConfigure initWithAppkey:@"6565a067b2f6fa00ba8869bc" channel:@"App Store"];
    [UMConfigure setLogEnabled:YES];
    
//    ///初始化穿山甲
//    [BUAdSDKManager setGDPR:0];
//    [BUAdSDKManager setCoppa:0];
//    #if DEBUG
//    // Whether to open log. default is none.
//    [BUAdSDKManager setLoglevel:BUAdSDKLogLevelDebug];
//    #endif
//    [BUAdSDKManager setAppID:CSJ_APPID];
//    [BUAdSDKManager setIsPaidApp:NO];
    
    [UMSocialGlobal shareInstance].universalLinkDic =@{@(UMSocialPlatformType_WechatSession):@"https://dm.3dliveo.com/",
    @(UMSocialPlatformType_QQ):@"https://dm.3dliveo.com/qq_conn/1111998114"};
    
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:@"WX_APPID" appSecret:@"WX_APPSECRET" redirectURL:@"https://cook.bizhijingling.com/"];
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_QQ appKey:@"QQ_APPID" appSecret:@"QQ_APPKey" redirectURL:@"https://cook.bizhijingling.com/"];

//    ///获取idfa
//    if (@available(iOS 14, *)) {
//        //申请权限
//        [ATTrackingManager requestTrackingAuthorizationWithCompletionHandler:^(ATTrackingManagerAuthorizationStatus status) {
////            NSLog(@"%@",[[ASIdentifierManager sharedManager] advertisingIdentifier]);
//            NSString *idfaStr = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
//            [BUAdSDKManager setCustomIDFA:idfaStr];
//        }];
//    }
    

}

- (void)initIQKeyboardManager {
    IQKeyboardManager *keyboardManager = [IQKeyboardManager sharedManager];
    keyboardManager.enable = YES;
    keyboardManager.shouldResignOnTouchOutside = YES;
    keyboardManager.enableAutoToolbar = NO;
    keyboardManager.keyboardDistanceFromTextField = 61 + 12;
    [keyboardManager registerTextFieldViewClass:[YYTextView class] didBeginEditingNotificationName:YYTextViewTextDidBeginEditingNotification didEndEditingNotificationName:YYTextViewTextDidEndEditingNotification];
}

/// 初始化facebook
- (void)createFaceBook:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [FBSDKSettings setAdvertiserTrackingEnabled:YES];
    FBSDKSettings.autoLogAppEventsEnabled = YES;
    BOOL s = [[FBSDKApplicationDelegate sharedInstance] application:application didFinishLaunchingWithOptions:launchOptions];
    NSLog(@"ddddd====%d",s);

    //设置延迟深度链接
        if (launchOptions[UIApplicationLaunchOptionsURLKey] == nil) {
            [FBSDKAppLinkUtility fetchDeferredAppLink:^(NSURL *url, NSError *error) {
                if (error) {
                    NSLog(@"Received error while fetching deferred app link %@", error);
                }
                if (url) {
                    //延时一秒钟启動深度連接
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:^(BOOL success) {
                        }];
                    });
                }
            }];
        }
}

- (void)initAppsFlyer {
    // AppsFlyer
    [AppsFlyerLib shared].appsFlyerDevKey = WS_FLYER_KEY;
    [AppsFlyerLib shared].appleAppID = WS_APPSTORY_ID;
    [AppsFlyerLib shared].delegate = self;
    if (@available(iOS 14, *)) {
        [[AppsFlyerLib shared] waitForATTUserAuthorizationWithTimeoutInterval:60];
    }
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sendLaunch:) name:UIApplicationDidBecomeActiveNotification object:nil];
}

- (void)sendLaunch:(UIApplication *)application {
    [[AppsFlyerLib shared] start];
}

- (void)initLoginPage {
    UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"WSLoginController" bundle:nil];
    WSLoginController *originVC = [storyBoard instantiateInitialViewController];
    BaseNavigationController * originNav = [[BaseNavigationController alloc]initWithRootViewController:originVC];
    originNav.navigationBarHidden = YES;
    self.window.rootViewController = originNav;
}

- (void)initMainPage {
    UIViewController *mainVC;
//    if(appUserCenter.isLogin) {
//        [self getUserInfocharonTV_Request];
//        BaseNavigationController * nav = [[BaseNavigationController alloc]initWithRootViewController:[BaseTabBarController new]];
//        nav.navigationBarHidden = YES;
//        mainVC = nav;
//    }
//    else {
//        UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"WSLoginController" bundle:nil];
//        WSLoginController *originVC = [storyBoard instantiateInitialViewController];
//        BaseNavigationController * originNav = [[BaseNavigationController alloc]initWithRootViewController:originVC];
//        originNav.navigationBarHidden = YES;
//        mainVC = originNav;
//    }
    
    NSString *str = [appUserDefaults objectForKey:@"TVFirstBeginYinDao"];
    if ([str isNotBlank]){
        [self getUserInfocharonTV_Request];
        BaseNavigationController * nav = [[BaseNavigationController alloc]initWithRootViewController:[BaseTabBarController new]];
        nav.navigationBarHidden = YES;
        mainVC = nav;
    }else{
        UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"WSFirstPopupViewController" bundle:nil];
        WSFirstPopupViewController *originVC = [storyBoard instantiateViewControllerWithIdentifier:@"WSFirstPopupViewController"];
        BaseNavigationController * originNav = [[BaseNavigationController alloc]initWithRootViewController:originVC];
        originNav.navigationBarHidden = YES;
        mainVC = originNav;
    }

    self.window.rootViewController = mainVC;
}

- (void)pushHome{
    BaseNavigationController * nav = [[BaseNavigationController alloc]initWithRootViewController:[BaseTabBarController new]];
    nav.navigationBarHidden = YES;
    self.window.rootViewController = nav;
}


- (void)initAD{
    [[GADMobileAds sharedInstance] startWithCompletionHandler:^(GADInitializationStatus * _Nonnull status) {
        
    }];
}

- (void)loadConfig {
    [WSAppDelegateRequest loadcharonTV_Config];
}

- (void)getUserInfocharonTV_Request {
    if(appUserCenter.isLogin) {
        [appUserCenter getUserInfocharonTV_Request];
    }
}
#pragma mark - UISceneSession lifecycle
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options{
//        [[FBSDKApplicationDelegate sharedInstance]application:app openURL:url options:options];
    //6.3的新的API调用，是为了兼容国外平台(例如:新版facebookSDK,VK等)的调用[如果用6.2的api调用会没有回调],对国内平台没有影响。
  [[UMSocialManager defaultManager]  handleOpenURL:url options:options];
    [WXApi handleOpenURL:url delegate:self];
    return YES;
}

- (void)applicationDidBecomeActive:(UIApplication *)application{
    [self tryToPresentAd];
    [FBSDKAppEvents activateApp];
    if (@available(iOS 14, *)) {
        //申请权限
        [ATTrackingManager requestTrackingAuthorizationWithCompletionHandler:^(ATTrackingManagerAuthorizationStatus status) {
            if (status == ATTrackingManagerAuthorizationStatusAuthorized){
                [FBSDKSettings setAdvertiserTrackingEnabled:YES];
            }else{
                [FBSDKSettings setAdvertiserTrackingEnabled:NO];
            }
        }];
    }
}

- (void)requestAppOpenAd {
  self.appOpenAd = nil;
  [GADAppOpenAd loadWithAdUnitID:WS_GOOGLE_OPENAD_KEY
                         request:[GADRequest request]
                     orientation:UIInterfaceOrientationPortrait
               completionHandler:^(GADAppOpenAd *_Nullable appOpenAd, NSError *_Nullable error) {
                 if (error) {
                   NSLog(@"Failed to load app open ad: %@", error);
                   return;
                 }
                 self.appOpenAd = appOpenAd;
               }];
}

- (void)tryToPresentAd {
  if (self.appOpenAd) {
    UIViewController *rootController = self.window.rootViewController;
    [self.appOpenAd presentFromRootViewController:rootController];
  } else {
    // If you don't have an ad ready, request one.
    [self requestAppOpenAd];
  }
}

- (void)reloadMain {
//    [self initMainPage];
    UIViewController * vc = self.window.rootViewController;
    if ([vc isKindOfClass:NSClassFromString(@"BaseNavigationController")]) {
        BaseNavigationController * nav = self.window.rootViewController;
        vc = nav.viewControllers.firstObject;
        UIViewController *mainVC;
        if ([vc isKindOfClass:NSClassFromString(@"BaseTabBarController")]) {
            BaseNavigationController * nav = [[BaseNavigationController alloc]initWithRootViewController:[BaseTabBarController new]];
            nav.navigationBarHidden = YES;
            mainVC = nav;
        }
        else {
            UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"WSLoginController" bundle:nil];
            WSLoginController *originVC = [storyBoard instantiateInitialViewController];
            BaseNavigationController * nav = [[BaseNavigationController alloc]initWithRootViewController:originVC];
            nav.navigationBarHidden = YES;
            mainVC = nav;
        }
        self.window.rootViewController = mainVC;
    }
    [self.window makeKeyAndVisible];
}

#pragma mark - UISceneSession lifecycle

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{
    //6.3的新的API调用，是为了兼容国外平台(例如:新版facebookSDK,VK等)的调用[如果用6.2的api调用会没有回调],对国内平台没有影响
    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url sourceApplication:sourceApplication annotation:annotation];
    if (!result) {
        // 其他如支付等SDK的回调
         return YES;
    }
    return result;
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url{
    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url];
    if (!result) {
        // 其他如支付等SDK的回调r
        return YES;
    }
    return result;
}

- (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray<id<UIUserActivityRestoring>> * _Nullable))restorationHandler{
    NSURL *url = userActivity.webpageURL;
//    [WXApi handleOpenUniversalLink:userActivity delegate:self];
    
    [[UMSocialManager defaultManager] handleUniversalLink:userActivity options:nil];
    return YES;
}

@end
